import { defineComponent, ref, reactive, inject } from 'vue'
import type { Ref } from 'vue'
import { useFullscreen } from '@vueuse/core'
import type { FormInst, FormRules } from 'naive-ui'
import { NButton, useMessage, NModal, NForm, NFormItem, NInput, NInputNumber } from 'naive-ui'
import AblumListApi from '@/service/api/yang/album/list'
import pageStyle from '@/theme/common.module.scss'
import MacHeader from '@/components/codeBlock/MacHeader'
interface formState {
  id?: number
  name: string
  annotate: string
  author: string
  avatar: string
  cover: string
  sort: number
}
interface editState {
  show: boolean
  title: string
  queryForm: formState
}
export default defineComponent({
  emits: ['success'],
  setup(_, { emit, expose }) {
    const $clone = inject('$clone') as <T>(data: T) => T
    const modalRef: Ref<any> = ref()
    const { isFullscreen, toggle }: { isFullscreen: Ref<boolean>; toggle: () => Promise<void> } =
      useFullscreen(modalRef)
    const toast = useMessage()

    const initForm: formState = {
      name: '',
      annotate: '',
      author: '',
      avatar: '',
      cover: '',
      sort: 1
    }
    const state: editState = reactive({
      show: false,
      title: '添加',
      queryForm: $clone(initForm)
    })
    const rules: FormRules = {
      name: [
        {
          required: true,
          message: '请输入标题',
          trigger: 'blur'
        }
      ],
      author: [
        {
          required: true,
          message: '请输入作者',
          trigger: 'blur'
        }
      ],
      avatar: [
        {
          required: true,
          message: '请上传头像',
          trigger: 'blur'
        }
      ],
      cover: [
        {
          required: true,
          message: '请上传封面',
          trigger: 'blur'
        }
      ],
      sort: [
        {
          required: true,
          message: '请输入权重',
          trigger: 'blur'
        }
      ]
    }
    const formRef = ref<FormInst | null>(null)
    const handleValidateClick = (e: MouseEvent): void => {
      e.preventDefault()
      formRef.value?.validate((errors: any): void => {
        if (!errors) {
          save()
        }
      })
    }

    const save = async (): Promise<void> => {
      const params: formState = $clone(state.queryForm)
      if (params?.id) {
        const { code, message } = await AblumListApi.edit(params)
        if (code !== 200) {
          toast.error(message)
          return
        }
        toast.success('编辑成功')
      } else {
        const { code, message } = await AblumListApi.add(params)
        if (code !== 200) {
          toast.error(message)
          return
        }
        toast.success('添加成功')
      }
      emit('success')
      close()
    }
    const close = (): void => {
      state.queryForm = $clone(initForm)
      state.show = false
    }

    const open = (row?: any): void => {
      state.title = '添加'
      if (row) {
        state.queryForm = $clone(row)
        state.title = row?.id ? '编辑' : '添加'
      }
      state.show = true
    }

    expose({
      open
    })
    return () => (
      <NModal show={state.show} onUpdateShow={close}>
        <div ref={modalRef} class={pageStyle.modalEdit}>
          <MacHeader
            title={state.title}
            is-fullscreen={isFullscreen.value}
            show-desc={false}
            onToggle={toggle}
            onClose={close}
          />
          <div class="content">
            <NForm ref={formRef} model={state.queryForm} rules={rules}>
              <NFormItem label="名称" path="name">
                <NInput v-model:value={state.queryForm.name} placeholder="请输入" />
              </NFormItem>
              <NFormItem label="简介" path="name">
                <NInput
                  type="textarea"
                  v-model:value={state.queryForm.annotate}
                  placeholder="请输入"
                />
              </NFormItem>
              <NFormItem label="作者" path="author">
                <NInput v-model:value={state.queryForm.author} placeholder="请输入" />
              </NFormItem>
              <NFormItem label="头像" path="avatar">
                <NInput v-model:value={state.queryForm.avatar} placeholder="请输入" />
              </NFormItem>
              <NFormItem label="封面" path="cover">
                <NInput v-model:value={state.queryForm.cover} placeholder="请输入" />
              </NFormItem>
              <NFormItem label="权重">
                <NInputNumber
                  class="w-full"
                  v-model:value={state.queryForm.sort}
                  placeholder="请输入"
                />
              </NFormItem>
              <NFormItem>
                <div class="w-full flex justify-end">
                  <NButton type="primary" attr-type="button" onClick={handleValidateClick}>
                    <span>提交</span>
                  </NButton>
                </div>
              </NFormItem>
            </NForm>
          </div>
        </div>
      </NModal>
    )
  }
})
